package com.example.nuc_ms_beta.ui.viewcomponent.indviewpager;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.nuc_ms_beta.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 张博川 on 2016/8/30.
 */
public class ViewPagerIndicator extends LinearLayout{
    private Paint paint;
    private Path path;
    private int TriangleWidht, TriangleHeight;

    private static final float RADIO_TRIANGLE_WIDTH = 1 / 6F;//比例


    private int initTranslationX;//初始化偏移量
    private int moveingTranslationX;//移动中的偏移量
    private int translation = 0;
    private int visiableCount = 0;
    private List<String> titles = new ArrayList<String>();
    private static final int COLOR_TEXT_DEFAULT = 0xFFFFFFFF;//正常颜色 ff C4 C0 B8
    private static final int COLOR_TEXT_HIGHLIGHT = 0xFFFFFFFF;//高亮颜色#ED6460
    private ViewPager viewPager;
    private PagerOnChangeListener listener;

    public ViewPagerIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        //获取可见tab的数量
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator);
        visiableCount = a.getInt(R.styleable.ViewPagerIndicator_visiable_tab_count, 6);
        if (visiableCount <= 0) {
            visiableCount = 6;
        }
        a.recycle();
        initPaint();
    }

    public ViewPagerIndicator(Context context) {
        this(context, null);
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        TriangleWidht = (int) (w / visiableCount * RADIO_TRIANGLE_WIDTH);//三角形的底边宽度
        TriangleWidht = (int) Math.min(TriangleWidht, getScreenWidth() / 3 * RADIO_TRIANGLE_WIDTH);
        initTranslationX = w / visiableCount / 2 - TriangleWidht / 2;//初始值偏移量
        initTriangle();
    }

    //初始化画笔
    private void initPaint() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.parseColor("#FFFFFF"));
        paint.setStyle(Paint.Style.FILL);
        paint.setDither(true);
        paint.setPathEffect(new CornerPathEffect(4));//设置圆角
    }

    //通过Path 来构造三角形  || 同时绘制 白色下划线（需要开发）
    private void initTriangle() {
        //暂时设置角度为 45*
        TriangleHeight = TriangleWidht / 2;
        path = new Path();
        path.moveTo(0, 0);
        path.lineTo(TriangleWidht, 0);
        path.lineTo(TriangleWidht / 2, -TriangleHeight + 2);
        path.close();
    }

    //绘制组建子View进行绘制
    @Override
    protected void dispatchDraw(Canvas canvas) {
        canvas.save();
        canvas.translate(initTranslationX + translation, getHeight());
        canvas.drawPath(path, paint);
        canvas.restore();
        super.dispatchDraw(canvas);
    }

    //指示器 跟随手指进行滚动
    public void scroll(int position, float positionOffset) {
        //联动一  上不动
        int tabWidth = getWidth() / visiableCount;//确定每个tab的宽度
        // Log.e("positionOffSet:"+positionOffset," position:"+position);
        translation = (int) (tabWidth * (positionOffset + position));
        //联动二  上超出范围动  实现方式： 容器移动
        if (position >= (visiableCount - 2) && positionOffset > 0 && getChildCount() > visiableCount && position <= getChildCount() - 3) {
            if (visiableCount != 1) {
                this.scrollTo((int) ((position - (visiableCount - 2)) * tabWidth + (tabWidth * positionOffset)), 0);
            } else {//移动
                this.scrollTo((int) (position * tabWidth + tabWidth * positionOffset), 0);
            }
        }
        invalidate();
    }

    /*
    View加载完XML数据后，会回掉onFInishInflate(）
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        int CurrentCount = getChildCount();
        if (CurrentCount == 0) return;
        //设置子View的宽度
        for (int i = 0; i < CurrentCount; i++) {
            View view = getChildAt(i);
            LayoutParams lp = (LayoutParams) view.getLayoutParams();
            lp.weight = 0;
            lp.width = getScreenWidth() / visiableCount;
            view.setLayoutParams(lp);
            //可以在这里设置点击事件
            //setItemChildEvent();
        }

    }

    /*
    获取屏幕的宽度
     */
    private int getScreenWidth() {
        WindowManager manager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    //在这里设置点击事件
    public void setTabItemTitle(List<String> titles) {
        if (titles != null && titles.size() > 0) {
            this.removeAllViews();
            this.titles = titles;
            for (String title : this.titles) {
                this.addView(SonTextView(title));
            }
            setItemChildEvent();
        }
    }

    public void setVisiableTabCount(int count) {
        this.visiableCount = count;
    }

    //根据title 向父类添加View
    private View SonTextView(String title) {
        TextView textView = new TextView(getContext());
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        lp.width = getScreenWidth() / visiableCount;
        textView.setText(title);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
        textView.setTextColor(Color.parseColor("#E43F39"));
        textView.setLayoutParams(lp);
        return textView;
    }

    /*
    设置关联的ViewPager
     */
    public void setViewpager(ViewPager viewPager, int pos) {
        this.viewPager = viewPager;
        this.viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // 0 ----1  偏移量 tabWidth * positionOffset
                // 1 ----2 总的偏移量 tabWidth* positionOffes + positon+ tabWidth
                scroll(position, positionOffset);
                if (listener != null) {
                    listener.onPagerScrolled(position, positionOffset, positionOffsetPixels);
                }
            }

            @Override
            public void onPageSelected(int position) {
                if (listener != null) {
                    listener.onPagerSelected(position);
                }
                HighLightTextView(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                listener.OnPagerScrollStateChanged(state);
            }
        });
        HighLightTextView(pos);
        this.viewPager.setCurrentItem(pos);
    }

    /*
   由于把 PagerView的监听事件写在了自定义控件里面
    */
    public interface PagerOnChangeListener {
        public void onPagerScrolled(int position, float positionOffset, int positionOffsetPixels);

        public void onPagerSelected(int position);

        public void OnPagerScrollStateChanged(int state);
    }

    public void setPagerListener(PagerOnChangeListener listener) {
        this.listener = listener;
    }

    //设置字体高亮
    private void HighLightTextView(int pos) {
        ColorResetTextView();
        View view = getChildAt(pos);
        if (view instanceof TextView) {
            ((TextView) view).setTextColor(COLOR_TEXT_HIGHLIGHT);
            ((TextView) view).setTextSize(14);
        }
    }

    //设置字体颜色 恢复默认颜色
    private void ColorResetTextView() {
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            if (view instanceof TextView) {
                ((TextView) view).setTextSize(12);
                ((TextView) view).setTextColor(COLOR_TEXT_DEFAULT);
            }
        }
    }

    //设置tab的点击事件
    private void setItemChildEvent() {
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            final int j = i;
            View view = getChildAt(i);
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    viewPager.setCurrentItem(j);
                }
            });
        }
    }
}
